package logger

import (
	"github.com/rifflock/lfshook"
	"github.com/sirupsen/logrus"
	"naio/config"
	"naio/util"
	"time"
)

func init() {
	setLevel()
}

var levels = map[string]logrus.Level{
	"panic": logrus.PanicLevel,
	"fatal": logrus.FatalLevel,
	"error": logrus.ErrorLevel,
	"warn":  logrus.WarnLevel,
	"info":  logrus.InfoLevel,
	"debug": logrus.DebugLevel,
}

func setLevel() {
	levelConf := config.Config.LogLevel

	if levelConf == "" {
		levelConf = "info"
	}

	if level, ok := levels[levelConf]; ok {
		logrus.SetLevel(level)
	} else {
		logrus.SetLevel(logrus.DebugLevel)
	}
}

type LogParams struct {
	Ip         string      `json:"ip"`
	Method     string      `json:"method"`
	RequestUrI string      `json:"request_uri"`
	StatusCode int         `json:"status_code"`
	Duration   interface{} `json:"duration"`
	StartTime  string      `json:"start_time"`
	EndTime    string      `json:"end_time"`
}

var Logger *logrus.Logger

func Default() *logrus.Logger {
	if Logger != nil {
		return Logger
	}

	appDir := util.GetAppDir()
	today := time.Now().Format("2006-01-02")
	pathMap := lfshook.PathMap{
		logrus.InfoLevel:  appDir + "/runtime" + "/log/info_" + today + ".log",
		logrus.ErrorLevel: appDir + "/runtime" + "/log/error_" + today + ".log",
	}

	Logger = logrus.New()
	Logger.Hooks.Add(lfshook.NewHook(
		pathMap,
		&logrus.JSONFormatter{TimestampFormat: "2006-01-02 15:04:05"},
	))
	return Logger
}
